<?php
require_once("upyun/upyun.class.php");
class UpyunHelper{
    
    private $upyun ;
    private $base_url;
    
    function __construct($bucket, $user, $pwd) {
       $this->upyun = new UpYun("fourboy", "admin", "fourboy123");
       $this->base_url = "http://pic.fourboy.com";
    }

    public function upload($file,$root)
    {
        if (!is_file(DIR_IMAGE . $file)) {
            return;
        }
        
        $info = pathinfo($file);
        
        $extension = strtolower($info['extension']);
        
        $md5 = md5(file_get_contents(DIR_IMAGE . $file));
        $opts = array(
            UpYun::CONTENT_MD5 => $md5
        );
        $fh = fopen(DIR_IMAGE . $file, 'rb');
        $save_file = $root.'/'.date("Y/m/d",time()).'/'.$md5.'.' . $extension ;
        $rsp = $this->upyun->writeFile($save_file, $fh, True, $opts);   // 上传图片，自动创建目录
        fclose($fh);
        return $this->base_url . $save_file;
    }
    
    public function uploadWithPath($file,$save_file)
    {
        if (!is_file(DIR_IMAGE . $file)) {
            return "$file is not exist";
        }
        
        $md5 = md5(file_get_contents(DIR_IMAGE . $file));
        $opts = array(
            UpYun::CONTENT_MD5 => $md5
        );
        $fh = fopen(DIR_IMAGE . $file, 'rb');
        $rsp = $this->upyun->writeFile($save_file, $fh, True, $opts);   // 上传图片，自动创建目录
        fclose($fh);
        return $this->base_url . $save_file;
    }
    
    public function uploadWithFullPath($file,$save_file)
    {
        
        if (!is_file($file)) {
            return false;
        }
        
        $md5 = md5(file_get_contents($file));
        $opts = array(
            UpYun::CONTENT_MD5 => $md5
        );
        $fh = fopen($file, 'rb');
        $rsp = $this->upyun->writeFile($save_file, $fh, True, $opts);   // 上传图片，自动创建目录
        fclose($fh);
        return true;
    }

}